package dev.gtealib.com.opencv;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;

import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;
import com.linchaolong.android.imagepicker.cropper.CropImageView;

import org.opencv.core.Size;

import java.io.InputStream;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity {

    private String[] s_OPList = {
        "原图", "去色", "锐化", "对比度", "亮度", "中值滤波", "高斯滤波", "二值化"
    };

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private ImagePicker imagePicker;
    private Spinner spinner;
    private ImageView imageView;
    private Bitmap rawBmp;
    private Bitmap curBmp;

    class spinnerListener implements android.widget.AdapterView.OnItemSelectedListener{

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,  int position, long id) {
            switch (position){
                case 0:
                    curBmp = Bitmap.createBitmap(rawBmp);
                    break;
                case 1:
                    curBmp = OpenCVTools.Gray(curBmp);
                    break;
                case 2:
                    curBmp = OpenCVTools.Sharpen(curBmp);
                    break;
                case 3:
                    curBmp = OpenCVTools.Contrast(curBmp, 1.5);
                    break;
                case 4:
                    curBmp = OpenCVTools.Brightness(curBmp, 50);
                    break;
                case 5:
                    curBmp = OpenCVTools.MedianBlur(curBmp, 5);
                    break;
                case 6:
                    curBmp = OpenCVTools.GaussianBlur(curBmp,new Size(3,3), 5);
                    break;
                case 7:
                    curBmp = OpenCVTools.Threshold (curBmp,10,255);
                    break;
                default:
                    break;
            }

            imageView.setImageBitmap(curBmp);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            System.out.println("nothingSelect");
        }
    }

    protected void useImg(Uri url) {
        try {
            InputStream input = MainActivity.this.getContentResolver().openInputStream(url);
            rawBmp = BitmapFactory.decodeStream(input);
            curBmp = Bitmap.createBitmap(rawBmp);
            input.close();
            imageView.setImageBitmap(rawBmp);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }

    class openImagePickerListener implements  View.OnClickListener {
        @Override
        public void onClick(View view) {
            imagePicker.startGallery(MainActivity.this, new ImagePicker.Callback() {

                // 自定义裁剪配置
                /*@Override
                public void cropConfig(CropImage.ActivityBuilder builder) {
                    builder
                            // 是否启动多点触摸
                            .setMultiTouchEnabled(false)
                            // 设置网格显示模式
                            .setGuidelines(CropImageView.Guidelines.OFF)
                            // 圆形/矩形
                            .setCropShape(CropImageView.CropShape.RECTANGLE)
                            // 调整裁剪后的图片最终大小（单位：px）
                            .setRequestedSize(1920, 1080)
                            // 裁剪框宽高比
                            .setAspectRatio(16, 9);
                }
                */
                @Override
                public void cropConfig(CropImage.ActivityBuilder builder) {
                    builder
                            // 是否启动多点触摸
                            .setMultiTouchEnabled(false)
                            // 设置网格显示模式
                            .setGuidelines(CropImageView.Guidelines.OFF)
                            ;
                }

                @Override
                public void onPickImage(Uri url) {
                    useImg(url);
                }

                @Override
                public void onCropImage(Uri url) {
                    useImg(url);
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imagePicker = new ImagePicker();
        imagePicker.setCropImage(true);

        Button btnOpen = (Button) findViewById(R.id.btnOpen);
        spinner = (Spinner) findViewById(R.id.opList);
        imageView = (ImageView) findViewById(R.id.imageView);
        rawBmp = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        imageView.setImageBitmap(rawBmp);

        btnOpen.setOnClickListener(new openImagePickerListener());

        ArrayAdapter opAdapter = new ArrayAdapter(this, R.layout.listitem, R.id.textview, s_OPList);
        spinner.setAdapter(opAdapter);
        spinner.setOnItemSelectedListener(new spinnerListener());

        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}
